<?php

CCore::Using('base.collection');

class CCoreLabsWebMailMessage
{
	const OBJECT_ERROR_CODE = 2000;

	public $Index;
	public $Uid;
	public $Folder;
	public $Subject;
	public $Size;
	public $Date;
	public $From;
	public $To;
	public $Cc;
	public $Attachments;
	public $IsUnread;
	public $IsFlagged;
	public $Flags;
	public $Charset;

	/**
	 * @var CCoreMimeMessageBodyStructure
	 */
	public $BodyStrucrute;

	private $_mFormationCallback = null;

	public function InitFormationCallback($mFormationCallback)
	{
		$this->_mFormationCallback = $mFormationCallback;
	}

	public function CallbackPlainTextStreamParse($rStream, $sLiteralAtomUpperCase)
	{
		if (null !== $this->_mFormationCallback)
		{
			$oBodyStrucrutePlain = $this->BodyStrucrute->SearchPlainPart();
			if ($oBodyStrucrutePlain)
			{
				$sInlineDecodeFunctionName = CCoreMimeUtils::GetInlineDecodeFunctionName(
					$oBodyStrucrutePlain->MailEncodingName());
				
				$sCharset = $oBodyStrucrutePlain->Charset();
				if (empty($sCharset))
				{
					$sCharset = $this->Charset;
				}

				$rPlainStream = CCoreMimeStreamWrapper::CreateBinaryStream($rStream,
					$sInlineDecodeFunctionName, $sCharset, C_MIME_CHARSET_UTF8);

				call_user_func($this->_mFormationCallback, $this, 'plain', $rPlainStream);
			}
		}
	}

	public function CallbackHtmlTextStreamParse($rStream, $sLiteralAtomUpperCase)
	{
		if (null !== $this->_mFormationCallback)
		{
			$oBodyStrucruteHtml = $this->BodyStrucrute->SearchHtmlPart();
			if ($oBodyStrucruteHtml)
			{
				$sInlineDecodeFunctionName = CCoreMimeUtils::GetInlineDecodeFunctionName(
					$oBodyStrucruteHtml->MailEncodingName());
				$sCharset = $oBodyStrucruteHtml->Charset();
				if (empty($sCharset))
				{
					$sCharset = $this->Charset;
				}
				
				$rPlainStream = CCoreMimeStreamWrapper::CreateBinaryStream($rStream,
					$sInlineDecodeFunctionName, $sCharset, C_MIME_CHARSET_UTF8);

				call_user_func($this->_mFormationCallback, $this, 'html', $rPlainStream);
			}
		}
	}

	public function CallbackFullBodyStreamParse($rStream, $sLiteralAtomUpperCase)
	{
		if (null !== $this->_mFormationCallback && 'BODY[]' === $sLiteralAtomUpperCase)
		{
			$rFullBodyStream = CCoreMimeStreamWrapper::CreateBinaryStream($rStream);
			call_user_func($this->_mFormationCallback, $rFullBodyStream);
		}
	}
}

class CCoreLabsWebMailMessageCollection extends ACoreBaseCollection
{
	const OBJECT_ERROR_CODE = 2100;

	/**
	 * @return CCoreLabsWebMailMessageCollection
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * @param CCoreLabsWebMailMessage $WebMailMessage
	 * @return void
	 */
	public function Add(CCoreLabsWebMailMessage $WebMailMessage)
	{
		parent::Add($WebMailMessage);
	}
}